<template>
    <div>
      <h1>中值滤波处理</h1>
      <el-form :model="formData">
        <el-form-item label="滤波器大小 (kernel size) 推荐值5">
          <el-input v-model="formData.kernel_size" type="number" @change="validateKernelSize"></el-input>
        </el-form-item>
      </el-form>
      <file-upload @data-extracted="handleDataExtracted"></file-upload>
      <el-button type="primary" @click="processData" :disabled="!uploadedData || !isKernelSizeValid">开始处理</el-button>
      <el-progress v-if="loading" :percentage="progress"></el-progress>
      <line-chart 
        v-if="uploadedData && uploadedData.wavelengths.length && uploadedData.intensities.length"
        :x="uploadedData.wavelengths" 
        :y="uploadedData.intensities" 
        :fileName="uploadedData.fileName + ' (原始数据)'">
      </line-chart>
      <line-chart 
        v-if="processedData" 
        :x="processedData.wavelengths" 
        :y="processedData.intensities" 
        :fileName="uploadedData.fileName + ' (处理后数据)'">
      </line-chart>
    </div>
  </template>
  
  <script>
  import FileUpload from '@/components/FileUpload.vue';
  import LineChart from '@/components/LineChart.vue';
  
  export default {
    components: {
      FileUpload,
      LineChart
    },
    data() {
      return {
        formData: {
          kernel_size: null
        },
        uploadedData: null,
        loading: false,
        progress: 0,
        processedData: null,
        isKernelSizeValid: false
      };
    },
    methods: {
      validateKernelSize() {
        const size = this.formData.kernel_size;
        this.isKernelSizeValid = size && size % 2 === 1; // 必须是奇数
      },
      handleDataExtracted(data) {
        this.uploadedData = data;
      },
      processData() {
        if (!this.uploadedData) return;
  
        this.loading = true;
        this.progress = 0;
  
        const { kernel_size } = this.formData;
        const { wavelengths, intensities } = this.uploadedData;
  
        // 前端进行中值滤波
        const filteredIntensities = this.medianFilter(intensities, kernel_size);
  
        this.processedData = {
          wavelengths: wavelengths,
          intensities: filteredIntensities
        };
  
        this.loading = false;
      },
      medianFilter(data, kernel_size) {
        const half = Math.floor(kernel_size / 2);
        const filtered = [];
  
        for (let i = 0; i < data.length; i++) {
          const window = [];
  
          for (let j = -half; j <= half; j++) {
            const index = i + j;
            if (index >= 0 && index < data.length) {
              window.push(data[index]);
            }
          }
  
          window.sort((a, b) => a - b);
          filtered.push(window[Math.floor(window.length / 2)]);
        }
  
        return filtered;
      }
    }
  };
  </script>
  
  <style scoped>
  /* 添加样式以适应页面设计 */
  </style>
  